<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
      class="form-search"
    >
      <SearchTool
        :code="{
          factory: 'factoryCode',
          workshop: 'workshopCode',
          line: 'productionLine',
          section: 'processSection',
        }"
        v-model:factory="queryParams.factory"
        v-model:workshop="queryParams.workshopCode"
        v-model:line="queryParams.lineCode"
        v-model:section="queryParams.sectionCode"
      ></SearchTool>
      <!-- <el-form-item label="工厂" prop="factory">
        <el-select
          v-model="queryParams.factory"
          placeholder="请选择"
          style="width: 240px"
          clearable
          filterable
          @change="handleSearchListChange('factory')"
        >
          <el-option
            v-for="(item, index) in factoryOptions"
            :key="index"
            :label="item.deptName"
            :value="item.deptCode"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工段名称" prop="workSection">
        <el-select
          v-model="queryParams.workSection"
          placeholder="请选择"
          clearable
          filterable
          style="width: 240px"
          @change="handleSearchListChange('workSection')"
        >
          <el-option
            v-for="(item, index) in workshopOptions"
            :key="index"
            :label="item.deptName"
            :value="item.deptCode"
          >
          </el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="订单编号" prop="orderCode">
        <el-input
          v-model="queryParams.orderCode"
          placeholder="请输入订单编号"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品编号" prop="prodCode">
        <el-input
          v-model="queryParams.prodCode"
          placeholder="请输入产品编号"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="prodName">
        <el-input
          v-model="queryParams.prodName"
          placeholder="请输入产品名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="计划时间" prop="date">
        <el-date-picker
          v-model="queryParams.date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          style="width: 240px"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          filterable
          style="width: 240px"
        >
          <el-option
            v-for="dict in order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item class="searchItem">
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button
          :loading="syncLoading"
          type="warning"
          plain
          icon="Refresh"
          @click="handleSync"
          v-hasPermi="['prod:order:sync']"
        >
          同步ERP数据
        </el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="typeList"
      border
      max-height="550px"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" /> -->
      <el-table-column
        label="订单编号"
        prop="orderCode"
        width="140px"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <el-link type="primary" @click="handleDetail(scope.row)">
            {{ scope.row.orderCode }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column width="120px" label="产品编号" prop="prodCode" />
      <el-table-column width="120px" label="产品名称" prop="prodName" />
      <el-table-column width="100px" label="计划产量" prop="planNumber" />
      <!-- <el-table-column width="100px" label="已排产产量" prop="arrangeNumber" /> -->
      <el-table-column width="100px" label="实际产量" prop="actualNumber" />
      <el-table-column width="100px" label="单位" prop="unit" />
      <el-table-column width="100px" label="规格" prop="packages" />
      <el-table-column width="100px" label="型号" prop="model" />
      <el-table-column width="120px" label="计划开始时间" prop="planStartTime">
        <template #default="scope">
          <span>{{ scope.row.planStartTime || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column width="120px" label="计划结束时间" prop="planEndTime">
        <template #default="scope">
          <span>{{ scope.row.planEndTime || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column width="120px" label="实际开始时间" prop="actualStartTime">
        <template #default="scope">
          <span>{{ scope.row.actualStartTime || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column width="120px" label="实际结束时间" prop="actualEndTime">
        <template #default="scope">
          <span>{{ scope.row.actualEndTime || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column width="100px" label="工厂" prop="factoryName" />
      <el-table-column width="100px" label="工段" prop="workshopName" />
      <el-table-column width="100px" label="产线" prop="lineName" />
      <el-table-column width="100px" label="工艺段" prop="sectionName" />
      <el-table-column width="100px" label="来源" prop="source">
        <template #default="scope">
          <dict-tag :options="order_source" :value="scope.row.source" />
        </template>
      </el-table-column>
      <el-table-column width="100px" label="状态" prop="status">
        <template #default="scope">
          <dict-tag :options="order_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="100"
        fixed="right"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <!-- <el-button
            v-if="scope.row.status == 'PROGRESSING'"
            link
            type="primary"
            icon="Edit"
             v-hasPermi="['prod:order:edit']"
            @click="handleEnable(scope.row)"
            >拆解工单</el-button
          > -->
          <el-button
            v-if="scope.row.status == 'PROGRESSING'"
            link
            type="primary"
            icon="Edit"
            v-hasPermi="['prod:order:confirm']"
            @click="handleConfirmPro(scope.row, 'SCQR')"
          >
            生产确认
          </el-button>
          <el-button
            v-if="scope.row.status == 'IN_PRODUCTION'"
            style="margin-left: 0"
            link
            type="primary"
            icon="Edit"
            v-hasPermi="['prod:order:completed']"
            @click="handleConfirmPro(scope.row, 'WGQR')"
          >
            完工确认
          </el-button>
          <el-button
            style="margin-left: 0"
            v-if="scope.row.status == 'IN_PRODUCTION' && scope.row.count == 0"
            link
            type="primary"
            icon="Edit"
            v-hasPermi="['prod:order:cancel']"
            @click="handleConfirmPro(scope.row, 'QXQR')"
          >
            取消确认
          </el-button>
          <p v-if="scope.row.status == 'COMPLETED' || scope.row.status == 'PLANING'">-</p>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog v-model="dialogVisible" title="系统提示" width="420" :before-close="handleClose">
      <p>确定"{{ dialogVisibleRowInfo.prodName }}"生产完工吗？</p>
      <p>计划产量：{{ dialogVisibleRowInfo.planNumber }}</p>
      <p>已完工产量：{{ dialogVisibleRowInfo.actualNumber }}</p>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="sureSubmit()">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="order">
import {
  listOrder,
  // getOrder,
  // delOrder,
  // addOrder,
  updateOrder,
  syncERPOrderList,
} from "@/api/base/workOrder/order";
// import {
//   listWorkOrder,
//   getWorkOrder,
//   delWorkOrder,
//   addWorkOrder,
//   updateWorkOrder,
// } from "@/api/base/workOrder/workOrder";
// import { listShift } from "@/api/base/plan/shiftMgt/shiftMaintenance";
// import { listShiftGroup } from "@/api/base/plan/shiftMgt/shiftGroup";
import { getFactoryTree } from "@/api/system/dept";
import { syncERPInWh } from "@/api/warehouse/inStorehouse";
import DetailData from "./data";
import { getCurrentInstance, ref, toRefs, reactive } from "vue";
const { proxy } = getCurrentInstance();
const { order_status } = proxy.useDict("order_status");
console.log(order_status);
const typeList = ref([
  {
    id: 1,
    planCode: "CS001",
  },
]);
const { order_source } = proxy.useDict("order_source");
// const tableData = ref([]);
// const shiftGroupsList = ref([]);
// const planGroupList = ref([]);
// const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRange = ref([]);
const dialogVisible = ref(false);
const dialogVisibleRowInfo = ref({});
var factoryOptions = ref([]);
// var workshopOptions = ref([]);
// var lineOptions = ref([]);
// var processOptions = ref([]);
const syncLoading = ref(false);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    factory: "",
    workshopCode: "",
    lineCode: "",
    sectionCode: "",
  },
});

const { queryParams, form } = toRefs(data);
/** 查询设备类型列表 */
function getList() {
  loading.value = true;
  let newForm = JSON.parse(JSON.stringify(queryParams.value));
  if (queryParams.value?.date?.length) {
    newForm.planStartTime = queryParams.value.date[0] + " 00:00:00";
    newForm.planEndTime = queryParams.value.date[1] + " 23:59:59";
    delete newForm.date;
  }
  listOrder(proxy.addDateRange(newForm)).then((response) => {
    typeList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function getFactorys(query) {
  getFactoryTree(query).then((res) => {
    factoryOptions.value = res.data;
  });
}

// function handleSearchListChange(type) {
//   if (type == "factory") {
//     depeIdSelectList({
//       deptType: "workShop",
//       deptCode: queryParams.value.factory,
//     }).then((res) => {
//       workshopOptions.value = res.data;
//       lineOptions.value = [];
//       processOptions.value = [];
//       queryParams.value.workSection = "";
//       queryParams.value.productLine = "";
//       queryParams.value.sectionCode = "";
//     });
//   }
//   if (type == "workSection") {
//     depeIdSelectList({
//       deptType: "line",
//       deptCode: queryParams.value.workSection,
//     }).then((res) => {
//       lineOptions.value = res.data;
//       processOptions.value = [];
//       queryParams.value.productLine = "";
//       queryParams.value.sectionCode = "";
//     });
//   }
// }
function handleSync() {
  syncLoading.value = true;
  syncERPOrderList()
    .then((res) => {
      syncERPInWh()
        .then(() => {
          proxy.$modal.msgSuccess("订单同步成功");
          syncLoading.value = false;
          getList();
        })
        .catch(() => {
          syncLoading.value = false;
        });
    })
    .catch(() => {
      syncLoading.value = false;
    });
}
// /** 取消按钮 */
// function cancel() {
//   open.value = false;
//   reset();
// }

function handleDetail(row) {
  proxy.subPage(DetailData, { title: "订单详情", data: row });
}

/** 表单重置 */
// function reset() {
//   form.value = {
//     classesCode: "",
//     classesName: "",
//     classesMode: "",
//     planClassesScheduleList: [],
//     remark: "",
//   };
//   proxy.resetForm("formRef");
// }

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value.factory = "";
  queryParams.value.workshopCode = "";
  queryParams.value.lineCode = "";
  queryParams.value.sectionCode = "";
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// function getListShift(classesMode) {
//   listShift().then((res) => {
//     if (res.code == 200) {
//       shiftGroupsList.value = res?.rows || [];
//       let _datas = res.rows.find((item) => {
//         return item.classesMode == classesMode;
//       });
//       form.value.classesCode =
//         _datas?.classesCode || res.rows[0]?.classesCode || "";
//       tableData.value =
//         _datas?.planClassesScheduleList ||
//         res.rows[0]?.planClassesScheduleList ||
//         [];
//     }
//   });
// }

// function getListShiftGroup() {
//   listShiftGroup({
//     sectionCode: form.value.sectionCode,
//     pageNum: 1,
//     pageSize: 999,
//   }).then((response) => {
//     planGroupList.value = response?.rows || [];
//   });
// }

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
function sureSubmit() {
  const status = "COMPLETED";
  const tips = "操作成功";
  const ids = dialogVisibleRowInfo.value.id;
  updateOrder({ id: ids, status: status, count: dialogVisibleRowInfo.value.count }).then((res) => {
    dialogVisible.value = false;
    getList();
    proxy.$modal.msgSuccess(tips);
  });
}
function handleConfirmPro(row, type) {
  let msg = "";
  let status = "";
  let tips = "";
  // row.status == 'PROGRESSING' &&
  if (type == "SCQR") {
    msg = '确定开始生产"' + row.prodName + '"吗？';
    status = "IN_PRODUCTION";
    tips = "操作成功";
  }
  // row.status == 'IN_PRODUCTION'&&
  if (type == "WGQR") {
    msg = '确定"' + row.prodName + '"生产完工吗？';
    status = "COMPLETED";
    tips = "操作成功";
    dialogVisible.value = true;
    dialogVisibleRowInfo.value = row;
    return;
  }
  // row.status == 'IN_PRODUCTION' &&
  if (type == "QXQR") {
    msg = '确定"' + row.prodName + '"取消确认吗？';
    status = "PROGRESSING";
    tips = "操作成功";
  }
  const ids = row.id;
  proxy.$modal
    .confirm(msg)
    .then(function () {
      return updateOrder({ id: ids, status: status, count: row.count });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess(tips);
    })
    .catch(() => {});
}
// function handleEnable(row) {
//   proxy.$router.push({
//     path: "/workOrder/workOrderIndex",
//     query: {
//       parent: JSON.stringify(row),
//     },
//   });
// }

getList();
getFactorys();
</script>
